package com.lzx.adx.report.controller.v1.cps.meituan;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.lzs.adx.commmon.utils.DateUtils;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.MeiTuanMapper;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.MeituanOrderDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.dto.meituan.MeiTuanResponse;
import com.lzx.adx.report.entity.MeituanOrderEntity;
import com.lzx.adx.report.model.ks.request.KsReportRequest;
import com.lzx.adx.report.model.meituan.OrderCallBackRequest;
import com.lzx.adx.report.model.toutiao.TouTiaoRequest;
import com.lzx.adx.report.service.MeituanOrderService;
import com.lzx.adx.report.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 快手美团CPS
 */
@RestController
@RequestMapping("/toutiao/mt")
@Slf4j
public class TouTiaoMeiTuanController {

    @Resource
    private MeituanOrderService meituanOrderService;

    @Autowired
    private MeiTuanMapper tuanMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Resource
    private ReportService reportService;





    @GetMapping("/report")
    public ResponseEntity report(TouTiaoRequest touTiaoRequest) {
        log.info("头条->美团上报请求的参数为{}", JSON.toJSONString(touTiaoRequest));
        //广点通，转换
        ReportDTO reportDTO=reportMapper.toReportToutiaoReportDTO(touTiaoRequest);
        reportDTO.setBizRequestId(IdUtil.fastUUID());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JSON.toJSONString(touTiaoRequest));
        reportExecutor.execute(()->{
            reportService.saveData(reportDTO);
        });

        return ResponseEntity.ok(new Result());
    }





    /**
     * 接收订单推送的接口
     * @return
     */
    @RequestMapping("/callBack")
    public MeiTuanResponse orderCallBack(@RequestBody OrderCallBackRequest orderCallBackRequest,String dspId){
        log.info("接收到【头条-美团】的请求参数为{}", JsonUtils.toJsonString(orderCallBackRequest));

        try {
            //先吧数据存储起来
            MeituanOrderDTO meituanOrderDTO = tuanMapper.toMeituanOrder(orderCallBackRequest);
            meituanOrderDTO.setTradeTypes(StringUtils.join(orderCallBackRequest.getTradeTypeList(), ","));
            meituanOrderDTO.setCreateTime(new Date());
            meituanOrderDTO.setUpdateTime(new Date());
            meituanOrderDTO.setExtend(JSON.toJSONString(orderCallBackRequest));
            meituanOrderService.save(meituanOrderDTO);

            //根据时间点去推送
            String ordertime = meituanOrderDTO.getOrdertime();

            //请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("ordertime", DateUtils.convertToFormattedDate(Long.parseLong(ordertime)));
            params.put("dsp_id", dspId);
            List<ReportDTO> list = reportService.list(params);

            List<ReportDTO> dataReport = list.stream().filter(t -> StringUtils.isBlank(t.getResultType())).collect(Collectors.toList());
            ReportDTO reportDTO = null;
            if (CollectionUtil.isNotEmpty(dataReport)) {
                reportDTO = dataReport.get(0);
            }else{
                log.error("订单号为{} ，未匹配到合适的点击",orderCallBackRequest.getOrderid());
                return new MeiTuanResponse().err();
            }


//         JSONObject jsonObject=JSONObject.parseObject(result);
//         Integer resultCode = jsonObject.getInteger("result");
            updateOrderStatus(meituanOrderDTO.getId());
        }catch (Exception e){
            log.error("头条美团 出现异常的 订单号为{}",orderCallBackRequest.getOrderid());
            log.error("头条美团 处理快手-美团出现了异常，异常的错误为",e);
        }
            return new MeiTuanResponse().ok();
    }


    public void updateOrderStatus(Long id){
        //更新订单状态为已处理
        MeituanOrderEntity meituanOrderEntity = new MeituanOrderEntity();
        meituanOrderEntity.setId(id);
        meituanOrderEntity.setHandType(1);
        meituanOrderService.updateById(meituanOrderEntity);
    }
}
